package com.pactera.demo.security.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pactera.demo.base.entity.LoginUser;
import com.pactera.demo.base.service.ILoginUserService;
import com.pactera.demo.common.dto.ResponseResult;
import com.pactera.demo.common.enums.StatusCodeEnum;
import com.pactera.demo.common.exception.InvalidTokenException;
import com.pactera.demo.common.util.JwtTool;
import com.pactera.demo.common.util.ResponseUtil;
import com.pactera.demo.common.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * JWT token 认证过滤器
 * </p>
 *
 * @author chang.zhou
 * @version 1.0
 * @date Created in 2020/3/1 19:15
 */
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 如果已经通过认证,直接放行
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        try {
            jwtAuthentication(token,request);
        }catch (AuthenticationException e){
            ResponseUtil.jsonWriter(response, ResponseResult.fail(StatusCodeEnum.INVALID_TOKEN,e.getMessage()));
        }

        filterChain.doFilter(request, response);
    }

    private void jwtAuthentication(String token,HttpServletRequest request){
        if(StringUtils.hasText(token)){
            ILoginUserService loginUserService = SpringContextUtil.getBean("loginUserService");
            String userId = JwtTool.getClaim(token);
            if(userId == null) throw new InvalidTokenException("invalid token");
            LoginUser loginUser = loginUserService.getOne(new QueryWrapper<LoginUser>().lambda().eq(LoginUser::getUserId, userId));
            if(loginUser == null)throw new InvalidTokenException("UserDetails must not be null");

            boolean verify = JwtTool.verify(userId, loginUser.getPassword(), token);
            if(!verify)throw new InvalidTokenException("invalid token");

            Set<String> roleCodes = loginUserService.getRolesByUserId(userId);
            List<SimpleGrantedAuthority> authorities = roleCodes.stream().map(x -> new SimpleGrantedAuthority(x)).collect(Collectors.toList());
            // 构建用户认证token
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, authorities);
            usernamePasswordAuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 放入安全上下文中
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        }
    }
}
